<template>
  <view>
    <web-view ref="myWebView" :src=src @message="message"></web-view>
  </view>
</template>

<script>
import {broadcast, startPlay} from "@/api/iot/device";
import {requestAndroidPermission} from "@/utils/permission";
import {getElevator} from "@/api/iot/elevator";
import {useUserStore} from "@/store/modules/user";
import {encryptMd5} from "@/utils/encryption/crypto";

export default {
  data() {
    return {
      postMsg: null,
      listHeight: 1000,
      elevatorId: "", //电梯ID
      elevatorInfo: {},
      deviceId: null,
      channelId: null,
      wv: null, // 初始化 wv 属性
      webrtc: null,
      broadcastRtc: null,
      src: "",
    }
  },
  onReady() {
    // #ifdef APP-PLUS
    var currentWebview = this.$scope.$getAppWebview()
    setTimeout(() => {
      this.wv = currentWebview.children()[0]
      this.postMsg = this.appsendH5
    }, 300);
    // #endif
  },
  async onLoad(e) {
    // #ifdef H5
    setTimeout(() => {
      this.Frames = document.getElementsByTagName('iframe');
      this.mainFrame = this.Frames[0].contentWindow;
      this.postMsg = this.h5sendH5
    }, 500)
    // #endif

    // #ifdef H5
    // uniapp webview h5 通信 window.postMessage 方式
    // https://blog.csdn.net/qq_42313445/article/details/127068570
    window.addEventListener("message", (event) => {
      let data = event.data.data;
      // hybrid页面通过uni.webView.postMessage传递的data结构
      if (!!data) {
        console.log("uniapp H5接收到消息：", data);
        this.handMessage(data.arg.option, data.arg.message);
      }
    }, false)
    // #endif
    this.elevator = await getElevator(e.elevatorId);
    console.log("开始执行onLoad", this.elevator.numberCode);
    this.deviceId = this.elevator.numberCode.split("_")[0];
    this.channelId = this.elevator.numberCode.split("_")[1];
    this.elevatorId = e.elevatorId
    this.elevatorName = this.elevator.elevatorName;
    uni.setNavigationBarTitle({
      title: this.elevatorName,
    })
    this.src = "/hybrid/html/video.html?title=" + this.elevatorName;
  },
  methods: {
    appSendH5(param) {
      // #ifdef APP-PLUS
      console.log("uniapp发送消息", param);
      console.log("this.$scope", this.$scope);
      let webview = this.$scope.$getAppWebview().children()[0];
      webview.evalJS("getUniAppMessage('" + JSON.stringify(param) + "')");
      // #endif
      // #ifdef H5

      // #endif
    },
    async message(data) {
      console.log("uniapp APP接收到消息：", data);
      let messageOption = data.detail.data[0];
      let option = messageOption.option;
      await this.handMessage(option, messageOption.message);
    },
    async handMessage(option, message) {
      if (option === "ready") {
        let res = await startPlay(this.deviceId, this.channelId);
        this.webrtc = res.rtcs;
        // 页面加载完成后，准备播放
        this.appSendH5({
          option: "play",
          webrtc: this.webrtc
        });
      } else if (option === "broadcast") {
        let newVar = await requestAndroidPermission('android.permission.RECORD_AUDIO');
        let res = await broadcast(this.deviceId, this.channelId);
        let streamInfo = res.streamInfo.rtcs;
        const userStore = useUserStore();
        let pushKey = userStore.userInfo.pushKey;
        let sign = encryptMd5(pushKey);
        let broadcastUrl = streamInfo + "&sign=" + sign;
        this.appSendH5({
          option: "broadcastStart",
          broadcastUrl: broadcastUrl
        });
      } else if (option === "toast") {
        await uni.showToast({
          title: message,
          icon: 'none'
        });
      } else if (option === "saveScreenshot") {
        const result = await this.saveBase64ToPhotosAlbum(message);
        await uni.showToast({
          title: result,
          icon: 'none'
        });
      }
    },
    async saveBase64ToPhotosAlbum(base64) {
      // Android权限检查（仅Android生效）
      // #ifdef APP-ANDROID
      const checkPermission = async () => {
        return new Promise((resolve, reject) => {
          const Permission = 'android.permission.WRITE_EXTERNAL_STORAGE';
          plus.android.requestPermissions(
              [Permission],
              (e) => {
                if (e.deniedAlways.length > 0 || e.deniedPresent.length > 0) {
                  reject('存储权限被拒绝');
                } else {
                  resolve();
                }
              },
              (err) => {
                reject('权限请求失败');
              }
          );
        });
      };
      // #endif
      try {
        // #ifdef APP-ANDROID
        await checkPermission();
        // #endif
        let tempFilePath = '';
        return new Promise((resolve, reject) => {
          const bitmap = new plus.nativeObj.Bitmap('saveBitmap');
          bitmap.loadBase64Data(base64, () => {
            tempFilePath = `${plus.io.PUBLIC_DOWNLOADS}/${Date.now()}.png`;
            bitmap.save(tempFilePath, {}, async () => {
              bitmap.clear();
              try {
                await uni.saveImageToPhotosAlbum({
                  filePath: tempFilePath
                });
                // 清理临时文件（可选）
                plus.io.resolveLocalFileSystemURL(tempFilePath, (entry) => {
                  entry.remove();
                });
                resolve('保存成功,请在相册中查看！');
              } catch (err) {
                reject(`保存失败: ${err.message}`);
              }
            }, (err) => {
              bitmap.clear();
              reject(`图片保存失败: ${err.message}`);
            });
          }, (err) => {
            bitmap.clear();
            reject(`Base64加载失败: ${err.message}`);
          });
        });
      } catch (err) {
        // 统一错误处理
        const errMsg = err.message || err.toString();

        if (errMsg.includes('被拒绝') || errMsg.includes('denied')) {
          uni.showModal({
            title: '权限申请',
            content: '需要存储权限保存图片',
            success: (res) => {
              if (res.confirm) {
                // #ifdef APP-ANDROID
                plus.runtime.openURL(plus.android.getPackageName());
                // #endif
                // #ifdef APP-IOS
                plus.runtime.openURL('app-settings:');
                // #endif
              }
            }
          });
        }
        throw errMsg;
      }
    }
  }
}
</script>

<style scoped>
</style>
